﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace WPFLoaders
{
    /// <summary>
    /// Interaction logic for MultipleRings.xaml
    /// </summary>
    public partial class MultipleRings : UserControl
    {
        public MultipleRings()
        {
            InitializeComponent();

            Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            var r = new Random();

            foreach (FrameworkElement child in Grid.Children)
            {
                var glow = new Storyboard {Duration = new Duration(TimeSpan.FromSeconds(2)), RepeatBehavior = RepeatBehavior.Forever};
                var glowOpacity = new DoubleAnimation(0.5, 1, new Duration(TimeSpan.FromSeconds(1)))
                    {
                        AutoReverse = true
                    };

                glowOpacity.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("Opacity"));
                glow.Children.Add(glowOpacity);

                var sizeRatio = child.Width/ActualWidth;
                const double speed = 5.5;
                var duration = (r.Next(80, 100)/100.0)* speed * sizeRatio;
                var storyboard = new Storyboard { RepeatBehavior = RepeatBehavior.Forever };
                var rotation = new DoubleAnimation(0, 360, new Duration(TimeSpan.FromSeconds(duration))) { From = 0, To = 360 };
                rotation.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("RenderTransform.(RotateTransform.Angle)"));
                storyboard.Children.Add(rotation);

                child.RenderTransformOrigin = new Point(0.5, 0.5);
                child.RenderTransform = new RotateTransform(0);

                storyboard.Begin(child, true);

                var startTime = r.NextDouble()*duration;
                storyboard.Seek(child, TimeSpan.FromSeconds(startTime), TimeSeekOrigin.BeginTime);

                glow.Begin(child, true);
                glow.Seek(child, TimeSpan.FromSeconds(startTime), TimeSeekOrigin.BeginTime);
            }
        }
    }
}
